﻿using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace GraphDrawing2.Canvas
{
    public class CanvasController
    {
        public CanvasModel Model { get; private set; }

        public CanvasController()
        {
            Model = new CanvasModel();
        }

        public void OnDrawBackground(DrawingContext dc)
        {
            Model.ViewPort.Tick();
            foreach (var painter in Model.GetPainters(PaintStage.BACKGROUND))
                painter.Draw(dc);
        }

        public void OnDraw(DrawingContext dc)
        {
            foreach (var painter in Model.GetPainters(PaintStage.CONTENT))
                painter.Draw(dc);
            foreach (var painter in Model.GetPainters(PaintStage.POSTPROCESSING))
                painter.Draw(dc);
        }

        public void OnMouseDown(Point p, MouseButtons btn, Keys keyState)
        {
            Model.UpdateState(p, btn, keyState);
            NotifyListeners(listener => listener.OnMouseDown());
        }

        public void OnMouseMove(Point p, MouseButtons btn, Keys keyState)
        {
            Model.UpdateState(p, btn, keyState);
            NotifyListeners(listener => listener.OnMouseMove());
        }

        public void OnMouseUp(Point p, MouseButtons btn, Keys keyState)
        {
            Model.UpdateState(p, btn, keyState);
            NotifyListeners(listener => listener.OnMouseUp());
        }

        public void OnMouseWheel(int delta)
        {
            NotifyListeners(listener => listener.OnMouseWheel(delta));
        }

        public void OnKeyPressed()
        {
            NotifyListeners(listener => listener.OnKeyPressed());
        }

        void NotifyListeners(Action<IListener> action)
        {
            foreach (var listener in Model.Listeners.ToArray())
                action(listener);
        }

        public void Resize(Size newSize)
        {
            Model.ViewPort.Resize(newSize);
        }
    }
}